import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        # Труба после ТОС нефтепроводная ТЭСЦ-5
        return 'Труба термообработанная ТЭСЦ-5'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        product_up = None
        try:
            product = row["Первичный продукт"]
            carving = row["Тип резьбы <Производство>"]
            strength_class = row["Класс прочности <Производство>"]
            steel_mark = row["Марка стали <Производство>"]
            diametr = row["Диаметр, мм <Производство>"]
            carving_type = consolidator.carving_type(carving)
            strength_group = consolidator.strength_group_by_steel(strength_class,steel_mark)
            # strength_1 = consolidator.strength_by_steel(steel_mark)
            # strength_steel = consolidator.strength_mapping(strength_1,steel_mark)
            # gmsps = consolidator.get_gmsps(strength_steel[1],product)
            # thickness = row["Толщина стенки, мм <Производство>"]
            diametr = row["Диаметр, мм <Производство>"]
            diametr_led = consolidator.nearest_in_guid("Параметры по Продукту ТЭСЦ-5",
                f"`Производство`=='Труба после ТОС нефтепроводная ТЭСЦ-5' and `Продукт`=='{product}'",
                "Доп параметр1",
                diametr,
                "Доп параметр1")
            diametr_led_s = str(diametr_led).replace(".0","")
            print(f"product: {product}; strength_group: {strength_group}; diametr_led: {diametr_led_s}; ")
            # Наименование_УП = Продукт & Диам_тип & " ГО " & Гр_прочн & " " & Резьба_тип
            product_up=f"{product}{diametr_led_s} ГО {strength_group} {carving_type}"
            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__pipe_thermo_t5__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

